"""
@Project:study_platform
@File:serializer.py
@Author:韩晓雷
@Date:20:59
"""


import re
from rest_framework import serializers
from user.models import *
from rest_framework.validators import ValidationError


# 班级
class ClasssSer(serializers.ModelSerializer):
    school = serializers.PrimaryKeyRelatedField(queryset=SchoolModel.objects.all())
    school_name = serializers.SerializerMethodField()

    def get_school_name(self, obj):
        return obj.school.name

    class Meta:
        model = ClasssModel
        fields = "__all__"

    # 重写校验方法
    def validate(self, attrs):
        name = attrs.get("name")
        #
        if not re.findall(r"[A-Za-z]{1,5}\d{1,5}", name):
            raise ValidationError(f'{name}班级名称由字母加数字组成')

        return attrs

